package miggy.memory;

import miggy.SystemModel;
import miggy.api.config.ConfigurationException;
import miggy.api.config.MachineDefinition;
import miggy.api.cpu.Size;
import miggy.api.memory.MappedSpace;
import miggy.utils.TextUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.logging.Logger;

/*
//  Miggy - Java Amiga MachineCore
//  Copyright (c) 2008, Tony Headford
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
//  following conditions are met:
//
//    o  Redistributions of source code must retain the above copyright notice, this list of conditions and the
//       following disclaimer.
//    o  Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
//       following disclaimer in the documentation and/or other materials provided with the distribution.
//    o  Neither the name of the Miggy Project nor the names of its contributors may be used to endorse or promote
//       products derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
//  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
//  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
//  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
//  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// $Revision: 21 $
*/

public final class RomController implements MappedSpace
{
	private static Logger logger = Logger.getLogger("Miggy.Memory.ROM");
	protected ByteBuffer buffer;
	private int baseAddress;
	private int size;

	public static final int ROM_SIZE_256 = 262144;
	public static final int ROM_SIZE_512 = 524288;

	public RomController()
	{
	}

	/**
	 * Initialise the controller
	 *
	 * @param config Configuration object containing machine settings
	 * @throws miggy.api.config.ConfigurationException
	 *          if Configuration holds invalid information for this component
	 */
	public void init(MachineDefinition config) throws ConfigurationException
	{
		String romName = config.getRomFilename();

		try
		{
			File f = new File(romName);
			if(!f.exists())
			{
				String msg = "Specified ROM file (" + romName + ") does not exist";
				logger.severe(msg);
				throw new ConfigurationException(msg);
			}

			long romLen = f.length();
			if(romLen != ROM_SIZE_256 && romLen != ROM_SIZE_512)
			{
				String msg = "Expected ROM file to be either " + ROM_SIZE_256 + " or " + ROM_SIZE_512 + " bytes but file is " + romLen + " bytes";
				logger.severe(msg);
				throw new ConfigurationException(msg);
			}

			size = (int)(romLen / 1024);
			buffer = ByteBuffer.allocateDirect((int)romLen);

			FileInputStream fis = new FileInputStream(f);
			FileChannel fc = fis.getChannel();

			int count = fc.read(buffer);
			logger.info("Read ROM file '" + romName + "' (" + count + " bytes)");
			fc.close();
			buffer.rewind();

			int sig = buffer.getInt(0);
			if(sig == 0x414d4952)	//AMIROMTYPE - Cloanto encrypted rom
			{
				//todo: handle these roms
				throw new IllegalArgumentException("Not handling encrypted ROM yet");
			}

			int chksum = 0, prev = 0;
			for(int i = 0; i < romLen; i += 4)
			{
				chksum += buffer.getInt(i);
				if(chksum < prev)
					chksum++;

				prev = chksum;
			}

			if(chksum != 0)
			{
				throw new ConfigurationException("Invalid ROM checksum (" + TextUtil.toHex(chksum) + ")");
			}

			int addr = buffer.getInt(4) & 0x00ff0000;
			if(addr != 0x00fc0000 && addr != 0x00f80000)
			{
				throw new ConfigurationException("Unexpected base ROM address (" + TextUtil.toHex(addr) + ")");
			}
			baseAddress = addr;
		}
		catch(IOException e)
		{
			String msg = "Problem reading ROM file '" + romName + "'";
			logger.severe(msg);
			throw new ConfigurationException(msg, e);
		}
	}

	public final void reset()
	{
		logger.info("Resetting ROM Controller");
	}

	/**
	 * Read a value from the specified address. The size of the data read is specified with the
	 * size parameter.
	 *
	 * @param address A 24-bit memory address
	 * @param size	DataSize value representing the size of the read.
	 * @return The value read from the address
	 */
	public int peek(int address, Size size)
	{
		int val;
		address -= baseAddress;

		switch(size)
		{
			case Byte:
			{
				val = buffer.get(address);
				break;
			}
			case Word:
			{
				val = buffer.getShort(address);
				break;
			}
			case Long:
			{
				val = buffer.getInt(address);
				break;
			}
			default:
				throw new IllegalArgumentException("Invalid data size specified");
		}
		return val & size.mask();
	}

	public final void poke(int address, int value, Size size)
	{
		logger.warning("ROM WRITE: Instruction at 0x" + TextUtil.toHex(SystemModel.CPU.getCurrentInstructionAddress()) + " attempted to write a -" + size.name() + "- value to ROM address: 0x" + TextUtil.toHex(address));
	}

	/**
	 * Read a value from the specified address without causing any side effects
	 * such as may happen when reading from custom chip registers. Used by the debugger.
	 * The size of the data read is specified with the size parameter.
	 *
	 * @param address A 24-bit memory address
	 * @param size	DataSize value representing the size of the read.
	 * @return The value read from the address
	 */
	public int directPeek(int address, Size size)
	{
		return peek(address, size);
	}

	/**
	 * Write a value into the specified address without causing any side effects
	 * such as may happen when reading from custom chip registers. Used by the debugger.
	 * The size of the write is specified with the size parameter.
	 *
	 * @param address A 24-bit memory address
	 * @param value   The value to be written. Value will be truncated to the specified size.
	 * @param size	DataSize value representing the size of the read.
	 */
	public void directPoke(int address, int value, Size size)
	{
	}

	public int getBaseAddress()
	{
		return baseAddress;
	}

	public int getSize()
	{
		return size;
	}
}
